使用GPT开发Idea自动写注释插件 您所在的位置:网站首页 idea 注解报错 使用GPT开发Idea自动写注释插件

使用GPT开发Idea自动写注释插件

2023-04-13 17:27| 来源: 网络整理| 查看: 265

拥有一个OpenAI账号注册不过多解释获取openai提供的API key用于访问openai的API。OpenAI API​​​​​​创建一个idea基本插件项目项目随便命名

创建后的文件结构CommentWriter是自己添加的

 

 开发准备导入OKHttp原生的http访问在打包后会报400错误HttpClient访问的接口在参数一致的情况下获取的结果非常蠢无法之间使用点击project structure点击加号再点击library点击new library点击form maven直接搜索Okhttp导入就可以了依赖的环境只有这个然后修改一下plugin.xml这里actions里面有两个方法一个是局部添加注释一个是全文添加注释但是有限制后面会提到 com.main.CommentWriter CommentWriter 1.5 com.intellij.modules.platform  然后把CommentWriter的代码添加一些两段代码我没做优化直接复制粘贴的有兴趣的可以自己优化一些 package com.main; import com.google.gson.Gson; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.WindowManager; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; import okhttp3.*; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; public class CommentWriter extends AnAction { @Override public void actionPerformed(AnActionEvent e) { Editor editor = e.getData(LangDataKeys.EDITOR); // 获取编辑器 if (editor != null) { StatusBar statusBar = WindowManager.getInstance().getStatusBar(editor.getProject()); // 获取状态栏 ApplicationManager.getApplication().runWriteAction(() -> { statusBar.setInfo("正在添加"); // 设置状态栏信息 System.out.println(editor.getDocument().getText().length()); // 输出文本长度 System.out.println(editor.getDocument().getText()); // 输出文本 if (editor.getDocument().getText().length() < 2000) { // 判断文本长度是否小于2000 String code = Comment_4(editor.getDocument().getText()); // 调用Comment_4函数 System.out.println(code); // 输出code if (code.length() >= editor.getDocument().getText().length()) { // 判断code长度是否大于等于文本长度 editor.getDocument().setText(code); // 设置文本 } statusBar.setInfo("添加完毕"); // 设置状态栏信息 } else { statusBar.setInfo("选中的文本太长无法添加注释"); // 设置状态栏信息 } }); } } public static String Comment_4(String code) { // 获取需要输出的文本 String prompt = "Please add Chinese comments above each line of the following Java code. Do not add comment symbols before import and package statements. Then return the complete code with comments. The code must not have fewer lines than the original." + code; // 调用generateText_3方法获取返回的文本 String result = generateText_3(prompt); // 解析JSON JSONObject jsonObject = (JSONObject) JSONValue.parse(result); JSONArray choices = (JSONArray) jsonObject.get("choices"); JSONObject firstChoice = (JSONObject) choices.get(0); Object textObj = firstChoice.get("text"); String textStr = textObj.toString(); // 返回带中文注释的代码 return textStr; } private static String generateText_3(String prompt) { // API相关参数 String API_KEY = "替换成你自己的APIkey"; String MODEL_ENDPOINT = "https://api.openai.com/v1/"; String MODEL_NAME = "text-davinci-003"; int MAX_TOKENS = 2048; double TEMPERATURE = 0; String response = ""; try { // 创建OkHttpClient OkHttpClient client = new OkHttpClient.Builder() .readTimeout(500, TimeUnit.SECONDS) .build(); // 创建RequestBody RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), createRequestBody(prompt, TEMPERATURE, MAX_TOKENS)); // 创建Request Request request = new Request.Builder() .url(MODEL_ENDPOINT + "engines/" + MODEL_NAME + "/completions") .post(requestBody) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer " + API_KEY).build(); // 发送请求 Response httpResponse = client.newCall(request).execute(); // 判断请求是否成功 if (httpResponse.isSuccessful()) { response = httpResponse.body().string(); } else { throw new RuntimeException("Failed : HTTP error code : " + httpResponse.code()); } } catch (IOException e) { e.printStackTrace(); } // 返回响应 return response; } private static String createRequestBody(String prompt, double temperature, int maxTokens) { // 创建Map Map requestBody = new HashMap(); // 添加参数 requestBody.put("prompt", prompt); requestBody.put("temperature", temperature); requestBody.put("max_tokens", maxTokens); // 转换为JSON return new Gson().toJson(requestBody); } } package com.main; import com.google.gson.Gson; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.WindowManager; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; import okhttp3.*; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; public class CommentWriterSelector extends AnAction { @Override public void actionPerformed(AnActionEvent e) { ApplicationManager.getApplication().runWriteAction(() -> { Project project = e.getProject(); if (project == null) { return; } StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); statusBar.setInfo("正在局部添加"); Editor editor = e.getData(LangDataKeys.EDITOR); if (editor != null) { SelectionModel selectionModel = editor.getSelectionModel(); String selectedText = selectionModel.getSelectedText(); System.out.println(selectedText.length()); System.out.println(selectedText); if (selectedText != null) { Document document = editor.getDocument(); if (editor.getSelectionModel().getSelectedText().length() > 2000) { statusBar.setInfo("文本过长"); return; } String code = Comment_4(editor.getSelectionModel().getSelectedText()); System.out.println(code); if (code.length() >= editor.getSelectionModel().getSelectedText().length()) { String allCode = document.getText(); System.out.println(allCode); allCode = allCode.replace(selectedText, code); System.out.println(allCode); document.setText(allCode); } statusBar.setInfo("局部添加完毕"); } } }); } public static String Comment_4(String code) { String prompt = "Please add Chinese comments above each line of the following Java code. Do not add comment symbols before import and package statements. Then return the complete code with comments. The code must not have fewer lines than the original." + code; String result = generateText_3(prompt); JSONObject jsonObject = (JSONObject) JSONValue.parse(result); JSONArray choices = (JSONArray) jsonObject.get("choices"); JSONObject firstChoice = (JSONObject) choices.get(0); Object textObj = firstChoice.get("text"); String textStr = textObj.toString(); return textStr; } private static String generateText_3(String prompt) { // API相关参数 String API_KEY = "替换成你自己的APIkey"; String MODEL_ENDPOINT = "https://api.openai.com/v1/"; String MODEL_NAME = "text-davinci-003"; int MAX_TOKENS = 2048; double TEMPERATURE = 0; String response = ""; try { // 创建OkHttpClient OkHttpClient client = new OkHttpClient.Builder() .readTimeout(500, TimeUnit.SECONDS) .build(); // 创建RequestBody RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), createRequestBody(prompt, TEMPERATURE, MAX_TOKENS)); // 创建Request Request request = new Request.Builder() .url(MODEL_ENDPOINT + "engines/" + MODEL_NAME + "/completions") .post(requestBody) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer " + API_KEY).build(); // 发送请求 Response httpResponse = client.newCall(request).execute(); // 判断请求是否成功 if (httpResponse.isSuccessful()) { response = httpResponse.body().string(); } else { throw new RuntimeException("Failed : HTTP error code : " + httpResponse.code()); } } catch (IOException e) { e.printStackTrace(); } // 返回响应 return response; } // 创建一个请求体 private static String createRequestBody(String prompt, double temperature, int maxTokens) { // 创建一个Map对象 Map requestBody = new HashMap(); // 将prompt放入Map中 requestBody.put("prompt", prompt); // 将temperature放入Map中 requestBody.put("temperature", temperature); // 将maxTokens放入Map中 requestBody.put("max_tokens", maxTokens); // 将Map转换为Json格式 return new Gson().toJson(requestBody); } }

然后就可以直接打包了右键点击项目点击最下面那个然后过一会就会自动打包好一个zip文件就在项目的目录。

 测试有两种方法一种是直接部署试试但是会有代码被直接替换的风险建议先备份

第一种直接部署

点击File-》Settings-》plugins-》instelled右边的设置图标然后点击install plugin from disk选中那个打包好的zip点击OK然后重启IDEA然后鼠标右键点击任意一个代码就出现两个按钮,第一格是为选中片段添加注释第二个是全文添加注释由于OpenAI的API访问限制一次最大只能接收2048长度的字符串所以对于过长的代码无法添加注释。

第二种运行方法是测试运行直接部署的是没有办法看到除了报错以外的其他信息的但是测试运行可以看到打印在控制台的内容

首先点击run-》然后edit configurations

 

 进入后点击左侧的加号点击plugins然后点击plugins在右侧页面点击add new run plugins

然后再VM option写入-Didea.is.internal=true -Didea.plugin.name=CommentWritername可以随便写。点击ok。

 然后再点击run后就会出现一个新的选项

点击后就可以运行了。然后会弹出一个测试使用的idea窗口就可以在里面操作右键的菜单然后主题窗口的控制台就会输出打印的内容。

效果

 

添加注释有时候会添加不进去因为chatGPT不会给所有语句都写注释

目前写的很简陋可以自己优化。

 

 

 

 

 

 

 

 

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有